#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QFileDialog"
#include "QFontDialog"
#include "QDebug"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowTitle("简单的记事本");

    //获取到菜单栏
    QMenuBar* menuBar = this->menuBar();

    //添加菜单
    QMenu* menu_file = new QMenu("文件");
    QMenu* menu_font = new QMenu("字体");

    menuBar->addMenu(menu_file);
    menuBar->addMenu(menu_font);

    //添加菜单项
    QAction* action_open = new QAction("打开");
    QAction* action_save = new QAction("保存");
    QAction* action_font = new QAction("调整字体");
    menu_file->addAction(action_open);
    menu_file->addAction(action_save);
    menu_font->addAction(action_font);

    edit = new QPlainTextEdit();
    this->setCentralWidget(edit);

    connect(action_open, &QAction::triggered, this, &MainWindow::handle_action_open);
    connect(action_save, &QAction::triggered, this, &MainWindow::handle_action_save);
    connect(action_font, &QAction::triggered, this, &MainWindow::handle_font);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handle_action_open()
{
    //打开文件对话框
    QString path = QFileDialog::getOpenFileName(this);

    //把文件名显示在状态栏
    QStatusBar* statusBar = this->statusBar();
    statusBar->showMessage(path);

    //根据用户选择的路径构建, QFile对象
    QFile file(path);
    bool ret = file.open(QIODevice::ReadOnly);
    if(!ret)
    {
        statusBar->showMessage(path + "打开失败");
        return;
    }

    QString text = file.readAll();

    file.close();

    edit->setPlainText(text);

}

void MainWindow::handle_action_save()
{
    QString path = QFileDialog::getSaveFileName(this);

    QStatusBar* statusBar = this->statusBar();
    statusBar->showMessage(path);

    QFile file(path);
    bool ret = file.open(QIODevice::WriteOnly);
    if(!ret)
    {
        statusBar->showMessage(path + "打开失败");
        return;
    }

    const QString& text = edit->toPlainText();
    file.write(text.toUtf8());

    file.close();
}

void MainWindow::handle_font()
{
    bool ok = false;
    QFont font = QFontDialog::getFont(&ok);

    this->edit->setFont(font);
}

